<?php

/**
 * The PagSeguro class handles the automatic return of the data of requests
 * made in PagSeguro
 * 
 * @author Cesar Augustus Silva <cesaraugustussilva@linuxmail.org>
 * @copyright Copyright (c) 2013, Cesar Augustus Silva
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL v3.0
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <­http://www.gnu.org/licenses/>.
 */
class PagSeguro {

    /** @var string The security token */
    protected $_token;
    
    /** @var string The error number of the PagSeguro */
    protected $_errno;
    
    /** @var string The error message of the PagSeguro */
    protected $_error;
    
    /**
     * The constructor magic method of the PagSeguro class
     * 
     * @param string $token The security token
     * @return void No value is returned
     */
    public function __construct($token = '') {
        $this->_token = $token;
    }
    
    /**
     * Finds whether a variable is NULL
     * 
     * @param mixed $var The variable being evaluated
     * @return bool <b>TRUE</b> if var is null or <b>FALSE</b> otherwise
     */
    protected function is_null($var) {
        if (is_array($var)) {
            if (count($var))
                return false;
            else
                return true;
        }
        else {
            if (!empty($var) && !is_null($var) && strlen(trim($var)))
                return false;
            else
                return true;
        }
    }
    
    /**
     * Prepare the data sent by PagSeguro and convert them to url,
     * adding the user token when needed.
     * 
     * @param array $post The return data request in PagSeguro
     * @param bool $add_token [optional]<br>
     *                           Defines if adds the token or not adds
     * @return string The url with the data
     */
    protected function prepare_data($post, $add_token = true) {
        if (!is_array($post))
            $post = array();
        if ($add_token) {
            $post['Comando'] = 'validar';
            $post['Token'] = $this->_token;
        }
        $data = array();
        foreach ($post as $key => $value) {
            if (!is_string($value))
                $value = '';
            else
                $value = urlencode(stripslashes($value));
            $data[] = $key.'='.$value;
        }
        return implode('&', $data);
    }
    
    /**
     * Check what type of dispatch of post
     * 
     * @return array The settings
     */
    protected function type_send() {
        if (function_exists('curl_exec'))
            $rtn = array('curl', 'https://pagseguro.uol.com.br/Security/NPI/Default.aspx');
        elseif ((PHP_VERSION >= 4.3) && ($fp = @fsockopen('ssl://pagseguro.uol.com.br', 443, $this->_errno, $this->_error, 30)))
            $rtn = array('fsocket', '/Security/NPI/Default.aspx', $fp);
        elseif ($fp = @fsockopen('pagseguro.uol.com.br', 80, $this->_errno, $this->_error, 30))
            $rtn = array('fsocket', '/Security/NPI/Default.aspx', $fp);
        else
            $rtn = array('', '');
        return $rtn;
    }
    
    /**
     * Verifies the type of open connection and sends the data received
     * 
     * @param array $post The return data request in PagSeguro
     * @param bool $type_send [optional]<br>
     *                        Defines the type of dispatch of post
     * @return bool <b>TRUE</b> on verified or <b>FALSE</b> on false
     */
    public function verify($post, $type_send = null) {
        if (!is_array($type_send))
            $type_send = $this->type_send();
        $data = $this->prepare_data($post);
        if (!in_array($type_send[0], array('curl', 'fsocket')))
            return false;
        $confirms = false;
        if ($type_send[0] == 'curl') {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $type_send[1]);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $resp = curl_exec($ch);
            if ($this->is_null($resp)) {
                curl_setopt($ch, CURLOPT_URL, $type_send[1]);
                $resp = curl_exec($ch);
            }
            curl_close($ch);
            $confirms = (strcmp($resp, 'VERIFICADO') == 0);
        }
        elseif ($type_send[0] == 'fsocket') {
            if (!$type_send[2]) {
                die($this->_error.' ('.$this->_errno.')');
            }
            else {
                $headers = 'POST '.$type_send[1].' HTTP/1.0'."\r\n";
                $headers .= 'Content-Type: application/x-www-form-urlencoded'."\r\n";
                $headers .= 'Content-Length: '.strlen($data)."\r\n\r\n";
                $resp = '';
                fwrite($type_send[2], $headers.$data);
                while (!feof($type_send[2])) {
                    $resp = fgets($type_send[2], 1024);
                    if (strcmp($resp, 'VERIFICADO') == 0) {
                        $confirms = true;
                        break;
                    }
                }
                fclose($type_send[2]);
            }
        }
        if ($confirms && function_exists('retorno_automatico')) {
            $itens = array(
                'VendedorEmail', 'TransacaoID', 'Referencia', 'TipoFrete',
                'ValorFrete', 'Anotacao', 'DataTransacao', 'TipoPagamento',
                'StatusTransacao', 'CliNome', 'CliEmail', 'CliEndereco',
                'CliNumero', 'CliComplemento', 'CliBairro', 'CliCidade',
                'CliEstado', 'CliCEP', 'CliTelefone', 'NumItens',
            );
            foreach ($itens as $item) {
                if (!isset($post[$item]))
                    $post[$item] = '';
                if ($item == 'ValorFrete')
                    $post[$item] = str_replace(',', '.', $post[$item]);
            }
            $products = array();
            for ($i = 1; isset($post['ProdID_'.$i]); $i++) {
                $products[] = array(
                    'ProdID' => $post['ProdID_'.$i],
                    'ProdDescricao' => $post['ProdDescricao_'.$i],
                    'ProdValor' => (double) (str_replace(',', '.', $post['ProdValor_'.$i])),
                    'ProdQuantidade' => $post['ProdQuantidade_'.$i],
                    'ProdFrete' => (double) (str_replace(',', '.', $post['ProdFrete_'.$i])),
                    'ProdExtras' => (double) (str_replace(',', '.', $post['ProdExtras_'.$i])),
                );
            }
            retorno_automatico(
                $post['VendedorEmail'], $post['TransacaoID'], $post['Referencia'],
                $post['TipoFrete'], $post['ValorFrete'], $post['Anotacao'],
                $post['DataTransacao'], $post['TipoPagamento'], $post['StatusTransacao'],
                $post['CliNome'], $post['CliEmail'], $post['CliEndereco'],
                $post['CliNumero'], $post['CliComplemento'], $post['CliBairro'],
                $post['CliCidade'], $post['CliEstado'], $post['CliCEP'],
                $post['CliTelefone'], $products, $post['NumItens']
            );
        }
        return $confirms;
    }

}